package com.lgx.mall.basic.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.lgx.common.basic.dao.GeneralDao;
import com.lgx.common.exception.DataException;
import com.lgx.common.web.Pagination;
import com.lgx.mall.basic.dao.INewsDao;
import com.lgx.mall.basic.entity.News;

/**
 * News DAO IMPL-CLASS
 * @author ZHANGCHAO
 *
 */
@Component("NewsDao")
public class NewsDao extends GeneralDao implements INewsDao{
	protected Logger log = Logger.getLogger(this.getClass());

	/**
	 * 添加
	 */
	@Override
	public News createNews(News news) throws DataException {
		this.getHibernateTemplate().save(news);
		log.info("[创建news]:"+news.getId());
		return news;
	}

	/**
	 * 修改
	 */
	@Override
	public News updateNews(News news) throws DataException {
		this.getHibernateTemplate().update(news);
		log.info("[修改news]:"+news.getId());
		return news;
	}

	/**
	 * 删除
	 */
	@Override
	public void deleteNews(News news) throws DataException {
		log.info("[删除news]:"+news.getId());
		this.getHibernateTemplate().delete(news);
	}

	/**
	 * 根据id删除
	 */
	@Override
	public void deleteNewsById(long id) throws DataException {
		log.info("[删除news]:"+id);
		this.deleteNews(this.findNewsById(id));
	}

	/**
	 * 更具ids批量删除
	 */
	@Override
	public void deleteNews(String[] ids) throws DataException {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 根具id查找news
	 */
	@Override
	public News findNewsById(long id) {
		return this.getHibernateTemplate().get(News.class, id);
	}

	/**
	 * 查询全部news
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<News> findNewsList() {
		String sql = "from News";
		return this.getHibernateTemplate().find(sql);
	}

	public Pagination findNewsPagination(int type,String starTime,String endTime,String author, int pageSize,int pageNum){
		String sql = "select n from News n where n.type = "+type;
		
		if(!StringUtils.isEmpty(author)){    //若果作者不为空则按照作者查询
			sql += " and (n.author like '%"+author+"%')";
		}
		
		if(!StringUtils.isEmpty(starTime)&&!StringUtils.isEmpty(endTime)){
			sql += "  and n.time between "+starTime+" and "+starTime;
		}
		
		sql += " order by n.layerOrder asc, n.time desc";
		
		return this.getListPagination(sql, new Object[]{}, pageSize, pageNum);
	}

}
